import * as fs from "fs"
import initSqlJs from "sql.js"
import * as path from "path"

export class CurrentUserGetter {
  /**
   * 获取当前用户邮箱
   */
  async getCurrentUser(dbPath: string): Promise<string | null> {
    console.log("=== CurrentUserGetter.getCurrentUser 开始 ===")
    console.log("dbPath:", dbPath)

    try {
      // 检查数据库文件是否存在
      if (!fs.existsSync(dbPath)) {
        console.log("数据库文件不存在")
        return null
      }

      // 初始化sql.js
      const SQL = await initSqlJs({
        locateFile: (file: string) => {
          const wasmPath = path.join(__dirname, "..", "node_modules", "sql.js", "dist", file)
          return wasmPath
        }
      })

      // 读取数据库
      const dbBuffer = fs.readFileSync(dbPath)
      const db = new SQL.Database(dbBuffer)

      // 查询当前用户邮箱
      const result = db.exec(
        "SELECT value FROM ItemTable WHERE key = ?",
        ["cursorAuth/cachedEmail"]
      )

      db.close()

      if (result.length > 0 && result[0].values.length > 0) {
        const email = result[0].values[0][0] as string
        console.log("当前用户:", email)
        return email
      } else {
        console.log("未找到当前用户")
        return null
      }
    } catch (error) {
      console.error("=== 获取当前用户失败 ===")
      console.error("错误详情:", error)
      return null
    }
  }
}

